/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * Compresses a file or directory into a Zip archive. Users of the class supply
 * the name of the file or directory as an argument.
 * 
 * @author Pablo Muñoz
 */
public class ZipCompressor {

	
	/* EXAMPLE:
	public static void main(String[] args) throws IOException {
		List<String> list = new ArrayList<String>();
		list.add("/path/to/file/1");
		list.add("/path/to/file/2");
		list.add("/path/to/file/3");
		list.add("/path/to/file/4");
		compress(list, "/path/to/destination/file.zip");
	}
	*/
	
	/** 
	 * Compress the files contained in the list in a zip file
	 * 
	 * @param paths 
	 * @param destinationPath
	 * @throws IOException
	 */
	public static void compress(List<String> paths, String destinationPath) throws IOException {
		ZipOutputStream zipOutputStream = new ZipOutputStream(
				new FileOutputStream(destinationPath));
		for (String path : paths) {
			addToZip(zipOutputStream, path);
		}
		zipOutputStream.close();
	}

	/** 
	 * Compress the files contained in the list in a zip file
	 * 
	 * @param paths 
	 * @param destinationPath
	 * @throws IOException
	 */
	public static void compress(String filePath, String destinationPath) throws IOException {
		ZipOutputStream zipOutputStream = new ZipOutputStream(
				new FileOutputStream(filePath + ".zip"));
		addToZip(zipOutputStream, filePath);
		zipOutputStream.close();
	}

	private static void addToZip(ZipOutputStream zipOutputStream, String path)
			throws IOException {
		byte[] buffer = new byte[1024];
		int len;
		File file = new File(path);
		ZipEntry zipEntry = new ZipEntry(file.getName());
		BufferedInputStream input = new BufferedInputStream(
				new FileInputStream(file));
		zipOutputStream.putNextEntry(zipEntry);
		while ((len = input.read(buffer)) >= 0) {
			zipOutputStream.write(buffer, 0, len);
		}
		input.close();
		zipOutputStream.closeEntry();
	}
}
